package com.example.interviewassistant;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

public class LlmApiService {
    private static final String TAG = "LlmApiService";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private final OkHttpClient client;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    private EventSource currentEventSource;
    private boolean isCancelled = false;

    public LlmApiService() {
        // 创建带有更长超时时间的OkHttpClient
        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public interface OnQuestionsGeneratedListener {
        void onQuestionsGenerating(String partialQuestion); // 流式响应过程中的部分结果
        void onQuestionsGenerated(List<InterviewQuestion> questions);
        void onError(String errorMessage);
    }
    
    /**
     * 取消当前正在进行的请求
     */
    public void cancelOngoingRequests() {
        isCancelled = true;
        if (currentEventSource != null) {
            try {
                currentEventSource.cancel();
                Log.d(TAG, "Cancelled ongoing request");
            } catch (Exception e) {
                Log.e(TAG, "Error cancelling request: " + e.getMessage());
            }
            currentEventSource = null;
        }
    }

    public void generateInterviewQuestions(Context context, String resumeText, QuestionGenerationConfig config, OnQuestionsGeneratedListener listener) {
        // 获取API配置
        ApiConfig apiConfig = new ApiConfigManager(context).getApiConfig();
        if (apiConfig == null || !apiConfig.isValid()) {
            listener.onError("API配置无效，请先配置API");
            return;
        }

        try {
            // 构建请求体，resumeText在传入前已经过脱敏
            String requestBody = buildRequestBody(resumeText, config, apiConfig);
            Request request = buildRequest(apiConfig, requestBody);
            executeRequest(context, request, listener);
        } catch (Exception e) {
            listener.onError("生成问题时出错: " + e.getMessage());
            Log.e(TAG, "Error generating questions", e);
        }
    }

    private String buildRequestBody(String resumeText, QuestionGenerationConfig config, ApiConfig apiConfig) throws JSONException {
        // 先构建系统提示
        StringBuilder systemPrompt = new StringBuilder();
        systemPrompt.append("你是一个经验丰富的技术面试官，擅长针对候选人的简历设计有难度且有针对性的技术面试问题。");
        systemPrompt.append("生成的问题应该直接与候选人的技能和经验相关，帮助面试官评估候选人的能力。");
        
        // 用于跟踪各类别领域是否被选中的标志
        boolean hasResearchDomains = false;
        boolean hasTechManagementDomains = false;
        boolean hasProjectManagementDomains = false;
        boolean hasRequirementAnalysisDomains = false;
        
        // 严格限定技术领域
        List<String> domains = config.getSelectedDomains();
        if (domains != null && !domains.isEmpty()) {
            systemPrompt.append("\n\n【核心指令】你必须严格限制在以下技术领域内出题，不要生成任何其他领域的问题：");
            
            // 按能力类别分组展示所选领域
            // 研发能力类别
            List<String> researchDomains = new ArrayList<>();
            for (String domain : domains) {
                if (isInCategory(domain, 0)) {
                    researchDomains.add(domain);
                    hasResearchDomains = true;
                }
            }
            
            // 技术管理能力类别
            List<String> techManagementDomains = new ArrayList<>();
            for (String domain : domains) {
                if (isInCategory(domain, 1)) {
                    techManagementDomains.add(domain);
                    hasTechManagementDomains = true;
                }
            }
            
            // 项目管理能力类别
            List<String> projectManagementDomains = new ArrayList<>();
            for (String domain : domains) {
                if (isInCategory(domain, 2)) {
                    projectManagementDomains.add(domain);
                    hasProjectManagementDomains = true;
                }
            }
            
            // 需求分析能力类别
            List<String> requirementAnalysisDomains = new ArrayList<>();
            for (String domain : domains) {
                if (isInCategory(domain, 3)) {
                    requirementAnalysisDomains.add(domain);
                    hasRequirementAnalysisDomains = true;
                }
            }
            
            // 添加研发能力领域
            if (hasResearchDomains) {
                systemPrompt.append("\n- 研发能力: ").append(String.join(", ", researchDomains));
            } else {
                systemPrompt.append("\n- 研发能力: 未选择任何研发领域，不要出研发类问题");
            }
            
            // 添加技术管理能力领域
            if (hasTechManagementDomains) {
                systemPrompt.append("\n- 技术管理能力: ").append(String.join(", ", techManagementDomains));
            } else {
                systemPrompt.append("\n- 技术管理能力: 未选择任何技术管理领域，不要出技术管理类问题");
            }
            
            // 添加项目管理能力领域
            if (hasProjectManagementDomains) {
                systemPrompt.append("\n- 项目管理能力: ").append(String.join(", ", projectManagementDomains));
            } else {
                systemPrompt.append("\n- 项目管理能力: 未选择任何项目管理领域，不要出项目管理类问题");
            }
            
            // 添加需求分析能力领域
            if (hasRequirementAnalysisDomains) {
                systemPrompt.append("\n- 需求分析能力: ").append(String.join(", ", requirementAnalysisDomains));
            } else {
                systemPrompt.append("\n- 需求分析能力: 未选择任何需求分析领域，不要出需求分析类问题");
            }
            
            // 强调再次提醒模型严格遵循领域限制
            systemPrompt.append("\n\n【特别强调】你必须仅出上述明确列出的具体技术领域的问题，完全避免未被明确列出的领域。");
            systemPrompt.append("\n如果某个大类（如研发能力）显示为未选择任何...领域则不要出该类问题，即使简历中有相关经历。");
        }
        
        // 添加问题类型指导（与技术领域区分）
        systemPrompt.append("\n\n【问题类型要求】每个问题无论技术领域如何，都必须按以下四种提问类型之一来设计：");
        systemPrompt.append("\n1. 客观知识型问题：有明确正确答案的问题，如概念解释、原理阐述、技术细节等；");
        systemPrompt.append("\n2. 实践经验型问题：考察实际操作能力和经验的问题，如如何实现某功能、解决某问题等；");
        systemPrompt.append("\n3. 思维评估型问题：有一定客观评判标准的分析类问题，如系统设计、技术选型、性能优化等；");
        systemPrompt.append("\n4. 主观开放型问题：探索候选人思维方式但需要有清晰评估框架的问题，如技术趋势判断、方案对比等。");
        
        systemPrompt.append("\n注意：上述是问题的类型，与问题的技术领域不同。每个技术领域都可以有这四种类型的问题。");
        systemPrompt.append("\n避免生成过于发散的问题，如\"你认为怎么样\"、\"你觉得为什么\"等缺乏客观评判标准的纯主观问题。");
        systemPrompt.append("\n所有问题必须有明确的考察点和可衡量的期望回答标准。");

        // 设置问题格式 - 使用更明确的格式规定
        systemPrompt.append("\n\n【格式要求】每个问题必须严格按照以下格式输出，确保问题类型为括号中的四种之一：");
        systemPrompt.append("\n问题 X: [客观知识型] 具体问题内容?");
        systemPrompt.append("\n考察点: 该问题的考察目的和重点");
        systemPrompt.append("\n期望回答: 一个理想的回答应该包含哪些要点");
        systemPrompt.append("\n\n问题类型必须是这四种之一：[客观知识型]、[实践经验型]、[思维评估型]、[主观开放型]");
        systemPrompt.append("\n请严格遵循此格式，包括问题类型的方括号。");

        // 难度设置
        if (config.getDifficulty() != null && !config.getDifficulty().isEmpty()) {
            systemPrompt.append("\n\n问题难度应为: ").append(config.getDifficulty());
        }
        
        // 重申技术领域限制
        if (domains != null && !domains.isEmpty()) {
            systemPrompt.append("\n\n【最终确认】再次检查你生成的每个问题，确保它们都严格限制在用户选择的技术领域内。");
            systemPrompt.append("\n不要生成任何在上面没有明确列出的技术领域的问题。");
            
            // 如果只选了特定类别的领域，再次强调
            if (hasResearchDomains && !hasTechManagementDomains && !hasProjectManagementDomains && !hasRequirementAnalysisDomains) {
                systemPrompt.append("\n用户只选择了研发能力领域，所有问题必须集中在研发技术上。");
            } else if (!hasResearchDomains && hasTechManagementDomains && !hasProjectManagementDomains && !hasRequirementAnalysisDomains) {
                systemPrompt.append("\n用户只选择了技术管理能力领域，所有问题必须集中在技术管理上。");
            } else if (!hasResearchDomains && !hasTechManagementDomains && hasProjectManagementDomains && !hasRequirementAnalysisDomains) {
                systemPrompt.append("\n用户只选择了项目管理能力领域，所有问题必须集中在项目管理上。");
            } else if (!hasResearchDomains && !hasTechManagementDomains && !hasProjectManagementDomains && hasRequirementAnalysisDomains) {
                systemPrompt.append("\n用户只选择了需求分析能力领域，所有问题必须集中在需求分析上。");
            }
        }
        
        // 打印最终的系统提示，便于调试
        System.out.println("发送给LLM的系统提示: " + systemPrompt.toString());

        // 创建JSON请求体
        JSONObject requestBody = new JSONObject();
        JSONArray messages = new JSONArray();

        // 添加系统消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", systemPrompt.toString());
        messages.put(systemMessage);

        // 简历内容在传入前已经过脱敏，不需要再次处理
        
        // 添加用户消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "基于以下简历内容，生成" + config.getQuestionCount() + "个针对性的技术面试问题，并为每个问题提供考察点和期望回答：\n\n" + resumeText);
        messages.put(userMessage);

        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("top_p", 0.95);
        requestBody.put("frequency_penalty", 0);
        requestBody.put("presence_penalty", 0);
        requestBody.put("max_tokens", 8192);
        
        // 添加流式响应参数
        requestBody.put("stream", true);
        
        // 对所有API类型添加model字段
        requestBody.put("model", apiConfig.getModelName());

        return requestBody.toString();
    }

    private void makeStreamingApiRequest(ApiConfig apiConfig, String requestBody, OnQuestionsGeneratedListener listener) {
        if (isCancelled) {
            return;
        }
        
        RequestBody body = RequestBody.create(requestBody, JSON);
        Request request = new Request.Builder()
                .url(apiConfig.getApiUrl())
                .addHeader("Authorization", "Bearer " + apiConfig.getApiKey())
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        // 创建用于保存完整响应的StringBuilder
        StringBuilder fullResponseBuilder = new StringBuilder();

        // 创建事件源监听器
        EventSourceListener eventSourceListener = new EventSourceListener() {
            @Override
            public void onOpen(EventSource eventSource, Response response) {
                Log.d(TAG, "Stream opened");
                fullResponseBuilder.setLength(0);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                if (isCancelled) {
                    eventSource.cancel();
                    return;
                }
                
                if (data.equals("[DONE]")) {
                    return;
                }

                try {
                    // 解析不同模型可能返回的不同JSON格式
                    JSONObject jsonData = new JSONObject(data);
                    String content = extractContentFromStreamEvent(jsonData, apiConfig.getModelType());
                    
                    if (content != null && !content.isEmpty()) {
                        fullResponseBuilder.append(content);
                        
                        // 向UI发送部分响应
                        if (!isCancelled) {
                            mainHandler.post(() -> {
                                listener.onQuestionsGenerating(fullResponseBuilder.toString());
                            });
                        }
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSON parse error: " + e.getMessage() + " in data: " + data);
                }
            }

            @Override
            public void onClosed(EventSource eventSource) {
                Log.d(TAG, "Stream closed");
                currentEventSource = null;
                
                if (isCancelled) {
                    return;
                }
                
                // 流结束时，解析完整响应并提取问题
                String fullResponse = fullResponseBuilder.toString();
                List<InterviewQuestion> questions = parseQuestionsWithDetails(fullResponse);
                
                mainHandler.post(() -> {
                    listener.onQuestionsGenerated(questions);
                });
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                Log.e(TAG, "Stream failed", t);
                currentEventSource = null;
                
                if (isCancelled) {
                    return;
                }
                
                String errorMessage = "Stream failed: " + (t != null ? t.getMessage() : "Unknown error");
                if (response != null) {
                    try {
                        ResponseBody responseBody = response.body();
                        if (responseBody != null) {
                            errorMessage = responseBody.string();
                        }
                    } catch (IOException e) {
                        errorMessage = "HTTP error: " + response.code() + " " + response.message();
                    }
                }

                Log.e(TAG, errorMessage);
                String finalError = errorMessage;
                mainHandler.post(() -> {
                    listener.onError(finalError);
                });
                
                eventSource.cancel();
            }
        };
        
        try {
            // 创建事件源并开始监听
            EventSource.Factory factory = EventSources.createFactory(client);
            currentEventSource = factory.newEventSource(request, eventSourceListener);
        } catch (Exception e) {
            Log.e(TAG, "Error creating EventSource", e);
            mainHandler.post(() -> {
                listener.onError("连接失败: " + e.getMessage());
            });
        }
    }
    
    // 从不同模型的流式响应中提取内容
    private String extractContentFromStreamEvent(JSONObject jsonData, String modelType) {
        try {
            // OpenAI格式 (GPT-3.5, GPT-4)
            if (modelType.startsWith("gpt-")) {
                if (jsonData.has("choices")) {
                    JSONArray choices = jsonData.getJSONArray("choices");
                    if (choices.length() > 0) {
                        JSONObject choice = choices.getJSONObject(0);
                        if (choice.has("delta")) {
                            JSONObject delta = choice.getJSONObject("delta");
                            if (delta.has("content")) {
                                return delta.getString("content");
                            }
                        }
                    }
                }
            } 
            // DeepSeek格式
            else if (modelType.equals(ApiConfigManager.MODEL_DEEPSEEK)) {
                if (jsonData.has("choices")) {
                    JSONArray choices = jsonData.getJSONArray("choices");
                    if (choices.length() > 0) {
                        JSONObject choice = choices.getJSONObject(0);
                        if (choice.has("delta")) {
                            JSONObject delta = choice.getJSONObject("delta");
                            if (delta.has("content")) {
                                return delta.getString("content");
                            }
                        }
                    }
                }
            }
            // 通用兜底格式 - 尝试各种可能的路径
            else {
                // 尝试choices.delta.content (OpenAI/DeepSeek格式)
                if (jsonData.has("choices")) {
                    JSONArray choices = jsonData.getJSONArray("choices");
                    if (choices.length() > 0) {
                        JSONObject choice = choices.getJSONObject(0);
                        // 尝试delta.content路径
                        if (choice.has("delta")) {
                            JSONObject delta = choice.getJSONObject("delta");
                            if (delta.has("content")) {
                                return delta.getString("content");
                            }
                        }
                        // 尝试text路径
                        else if (choice.has("text")) {
                            return choice.getString("text");
                        }
                        // 尝试message.content路径
                        else if (choice.has("message")) {
                            JSONObject message = choice.getJSONObject("message");
                            if (message.has("content")) {
                                return message.getString("content");
                            }
                        }
                    }
                }
                // 直接尝试content字段
                else if (jsonData.has("content")) {
                    return jsonData.getString("content");
                }
                // 记录找不到content的情况
                Log.w(TAG, "Could not extract content from: " + jsonData.toString());
            }
        } catch (JSONException e) {
            Log.e(TAG, "Error extracting content: " + e.getMessage());
        }
        return "";
    }

    private List<InterviewQuestion> parseQuestionsWithDetails(String text) {
        List<InterviewQuestion> questions = new ArrayList<>();
        
        try {
            // 尝试清理文本，去除可能的JSON格式混淆问题
            if (text.contains("\"object\"") && text.contains("\"model\"") && text.contains("\"choices\"")) {
                // 可能获取到了原始API响应，尝试提取content
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.has("choices")) {
                        JSONArray choices = json.getJSONArray("choices");
                        if (choices.length() > 0 && choices.getJSONObject(0).has("message")) {
                            JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                            if (message.has("content")) {
                                text = message.getString("content");
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error cleaning JSON response: " + e.getMessage());
                    // 继续尝试其他解析方法
                }
            }
            
            // 打印接收到的完整文本，便于调试
            Log.d(TAG, "解析问题文本: " + text);
            
            // 使用正则表达式匹配每个问题块，包含问题类型
            Pattern pattern = Pattern.compile("问题\\s*\\d+\\s*[:：]\\s*\\[(客观知识型|实践经验型|思维评估型|主观开放型)\\]\\s*(.*?)(?=\\s*考察点\\s*[:：])(\\s*考察点\\s*[:：]\\s*(.*?)(?=\\s*期望回答\\s*[:：]))(\\s*期望回答\\s*[:：]\\s*(.*?)(?=\\s*问题\\s*\\d+\\s*[:：]|$))", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(text);
            
            while (matcher.find()) {
                String questionType = matcher.group(1).trim();
                String question = matcher.group(2).trim();
                String keyPoints = matcher.group(4).trim();
                String expectedAnswer = matcher.group(6).trim();
                
                // 确保问题以问号结尾
                if (!question.endsWith("?") && !question.endsWith("？")) {
                    question = question + "?";
                }
                
                questions.add(new InterviewQuestion(questionType, question, expectedAnswer, keyPoints));
            }
            
            // 如果未匹配到指定格式问题，尝试更宽松的正则表达式
            if (questions.isEmpty()) {
                // 任意类型括号匹配
                Pattern patternAnyType = Pattern.compile("问题\\s*\\d+\\s*[:：]\\s*\\[([^\\]]+)\\]\\s*(.*?)(?=\\s*考察点\\s*[:：])(\\s*考察点\\s*[:：]\\s*(.*?)(?=\\s*期望回答\\s*[:：]))(\\s*期望回答\\s*[:：]\\s*(.*?)(?=\\s*问题\\s*\\d+\\s*[:：]|$))", Pattern.DOTALL);
                Matcher matcherAnyType = patternAnyType.matcher(text);
                
                while (matcherAnyType.find()) {
                    String questionType = matcherAnyType.group(1).trim();
                    String question = matcherAnyType.group(2).trim();
                    String keyPoints = matcherAnyType.group(4).trim();
                    String expectedAnswer = matcherAnyType.group(6).trim();
                    
                    // 根据类型进行标准化
                    if (questionType.contains("客观") || questionType.contains("知识")) {
                        questionType = "客观知识型";
                    } else if (questionType.contains("实践") || questionType.contains("经验")) {
                        questionType = "实践经验型";
                    } else if (questionType.contains("思维") || questionType.contains("评估")) {
                        questionType = "思维评估型";
                    } else if (questionType.contains("主观") || questionType.contains("开放")) {
                        questionType = "主观开放型";
                    } else {
                        questionType = "未分类";
                    }
                    
                    // 确保问题以问号结尾
                    if (!question.endsWith("?") && !question.endsWith("？")) {
                        question = question + "?";
                    }
                    
                    questions.add(new InterviewQuestion(questionType, question, expectedAnswer, keyPoints));
                }
            }
            
            // 尝试兼容旧格式，不含问题类型，但包含考察点和期望回答
            if (questions.isEmpty()) {
                Pattern oldPattern = Pattern.compile("问题\\s*\\d+\\s*[:：]\\s*(.*?)(?=\\s*考察点\\s*[:：])(\\s*考察点\\s*[:：]\\s*(.*?)(?=\\s*期望回答\\s*[:：]))(\\s*期望回答\\s*[:：]\\s*(.*?)(?=\\s*问题\\s*\\d+\\s*[:：]|$))", Pattern.DOTALL);
                Matcher oldMatcher = oldPattern.matcher(text);
                
                while (oldMatcher.find()) {
                    String question = oldMatcher.group(1).trim();
                    String keyPoints = oldMatcher.group(3).trim();
                    String expectedAnswer = oldMatcher.group(5).trim();
                    
                    // 处理可能嵌入在问题文本中的类型标记
                    String questionType = "未分类";
                    String cleanedQuestion = question;
                    
                    // 查找可能的类型标记 [xxx型]
                    Pattern typePattern = Pattern.compile("\\[([^\\]]+型)\\]");
                    Matcher typeMatcher = typePattern.matcher(question);
                    if (typeMatcher.find()) {
                        String foundType = typeMatcher.group(1);
                        // 根据类型进行标准化
                        if (foundType.contains("客观") || foundType.contains("知识")) {
                            questionType = "客观知识型";
                        } else if (foundType.contains("实践") || foundType.contains("经验")) {
                            questionType = "实践经验型";
                        } else if (foundType.contains("思维") || foundType.contains("评估")) {
                            questionType = "思维评估型";
                        } else if (foundType.contains("主观") || foundType.contains("开放")) {
                            questionType = "主观开放型";
                        }
                        
                        // 从问题中移除类型标记
                        cleanedQuestion = question.replaceAll("\\[([^\\]]+)\\]\\s*", "").trim();
                    }
                    
                    // 确保问题以问号结尾
                    if (!cleanedQuestion.endsWith("?") && !cleanedQuestion.endsWith("？")) {
                        cleanedQuestion = cleanedQuestion + "?";
                    }
                    
                    questions.add(new InterviewQuestion(questionType, cleanedQuestion, expectedAnswer, keyPoints));
                }
            }
            
            // 尝试只匹配问题和考察点
            if (questions.isEmpty()) {
                Pattern simplePattern = Pattern.compile("问题\\s*\\d+\\s*[:：]\\s*(.*?)(?=\\s*考察点\\s*[:：])(\\s*考察点\\s*[:：]\\s*(.*?)(?=\\s*问题\\s*\\d+\\s*[:：]|期望回答\\s*[:：]|$))", Pattern.DOTALL);
                Matcher simpleMatcher = simplePattern.matcher(text);
                
                while (simpleMatcher.find()) {
                    String question = simpleMatcher.group(1).trim();
                    String keyPoints = simpleMatcher.group(3).trim();
                    
                    // 处理可能嵌入在问题文本中的类型标记
                    String questionType = "未分类";
                    String cleanedQuestion = question;
                    
                    // 查找可能的类型标记 [xxx型]
                    Pattern typePattern = Pattern.compile("\\[([^\\]]+型)\\]");
                    Matcher typeMatcher = typePattern.matcher(question);
                    if (typeMatcher.find()) {
                        String foundType = typeMatcher.group(1);
                        // 根据类型进行标准化
                        if (foundType.contains("客观") || foundType.contains("知识")) {
                            questionType = "客观知识型";
                        } else if (foundType.contains("实践") || foundType.contains("经验")) {
                            questionType = "实践经验型";
                        } else if (foundType.contains("思维") || foundType.contains("评估")) {
                            questionType = "思维评估型";
                        } else if (foundType.contains("主观") || foundType.contains("开放")) {
                            questionType = "主观开放型";
                        }
                        
                        // 从问题中移除类型标记
                        cleanedQuestion = question.replaceAll("\\[([^\\]]+)\\]\\s*", "").trim();
                    }
                    
                    if (!cleanedQuestion.endsWith("?") && !cleanedQuestion.endsWith("？")) {
                        cleanedQuestion = cleanedQuestion + "?";
                    }
                    
                    questions.add(new InterviewQuestion(questionType, cleanedQuestion, "未提供期望回答", keyPoints));
                }
            }
            
            // 如果没有找到匹配的问题，尝试使用备用解析逻辑
            if (questions.isEmpty()) {
                questions = parseQuestionsFallback(text);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error parsing questions with details", e);
        }
        
        // 如果解析失败，添加一个错误提示
        if (questions.isEmpty()) {
            questions.add(new InterviewQuestion("未知", "API响应格式不符合预期，请检查配置或联系开发人员", 
                                             "无法解析期望回答", 
                                             "无法解析考察点"));
            Log.w(TAG, "Failed to parse questions from: " + text);
        }
        
        return questions;
    }
    
    private List<InterviewQuestion> parseQuestionsFallback(String text) {
        List<InterviewQuestion> questions = new ArrayList<>();
        
        try {
            // 尝试方法1：查找问题序号后跟随的文本
            Pattern numPattern = Pattern.compile("(?:问题|Q)\\s*(\\d+)\\s*[:：]\\s*(.*?)(?=[\\r\\n]+(?:问题|Q|\\d+\\s*[:：]|考察点|期望回答|$))", Pattern.DOTALL);
            Matcher numMatcher = numPattern.matcher(text);
            
            while (numMatcher.find()) {
                String question = numMatcher.group(2).trim();
                String questionType = "未分类";
                String cleanedQuestion = question;
                
                // 尝试从问题文本中提取类型标记 [xxx型]
                Pattern typePattern = Pattern.compile("\\[([^\\]]+)\\]");
                Matcher typeMatcher = typePattern.matcher(question);
                if (typeMatcher.find()) {
                    String foundType = typeMatcher.group(1);
                    // 根据类型关键字进行标准化
                    if (foundType.contains("客观") || foundType.contains("知识")) {
                        questionType = "客观知识型";
                    } else if (foundType.contains("实践") || foundType.contains("经验")) {
                        questionType = "实践经验型";
                    } else if (foundType.contains("思维") || foundType.contains("评估")) {
                        questionType = "思维评估型";
                    } else if (foundType.contains("主观") || foundType.contains("开放")) {
                        questionType = "主观开放型";
                    }
                    
                    // 从问题中移除类型标记
                    cleanedQuestion = question.replaceAll("\\[([^\\]]+)\\]\\s*", "").trim();
                }
                
                // 确保问题以问号结尾
                if (!cleanedQuestion.endsWith("?") && !cleanedQuestion.endsWith("？")) {
                    cleanedQuestion = cleanedQuestion + "?";
                }
                
                questions.add(new InterviewQuestion(questionType, cleanedQuestion, 
                        "未能解析期望回答", 
                        "未能解析考察点"));
            }
            
            // 如果方法1失败，尝试方法2：查找带序号的问题格式
            if (questions.isEmpty()) {
                Pattern bulletPattern = Pattern.compile("\\d+\\.\\s*(.*?[?？])", Pattern.DOTALL);
                Matcher bulletMatcher = bulletPattern.matcher(text);
                
                while (bulletMatcher.find()) {
                    String question = bulletMatcher.group(1).trim();
                    String questionType = "未分类";
                    String cleanedQuestion = question;
                    
                    // 尝试从问题文本中提取类型标记 [xxx型]
                    Pattern typePattern = Pattern.compile("\\[([^\\]]+)\\]");
                    Matcher typeMatcher = typePattern.matcher(question);
                    if (typeMatcher.find()) {
                        String foundType = typeMatcher.group(1);
                        if (foundType.contains("客观") || foundType.contains("知识")) {
                            questionType = "客观知识型";
                        } else if (foundType.contains("实践") || foundType.contains("经验")) {
                            questionType = "实践经验型";
                        } else if (foundType.contains("思维") || foundType.contains("评估")) {
                            questionType = "思维评估型";
                        } else if (foundType.contains("主观") || foundType.contains("开放")) {
                            questionType = "主观开放型";
                        }
                        
                        // 从问题中移除类型标记
                        cleanedQuestion = question.replaceAll("\\[([^\\]]+)\\]\\s*", "").trim();
                    }
                    
                    questions.add(new InterviewQuestion(questionType, cleanedQuestion, 
                            "未能解析期望回答", 
                            "未能解析考察点"));
                }
            }
            
            // 如果方法2失败，尝试方法3：提取任何可能的问句
            if (questions.isEmpty()) {
                Pattern questionPattern = Pattern.compile("([^.!?。！？\\r\\n]+[?？])", Pattern.DOTALL);
                Matcher questionMatcher = questionPattern.matcher(text);
                
                while (questionMatcher.find()) {
                    String potentialQuestion = questionMatcher.group(1).trim();
                    // 过滤掉太短的问句
                    if (potentialQuestion.length() > 10) {
                        questions.add(new InterviewQuestion("未分类", potentialQuestion, 
                                "未能解析期望回答", 
                                "未能解析考察点"));
                    }
                }
            }
            
            // 如果所有方法都失败，最后尝试：至少提取部分文本作为一个问题
            if (questions.isEmpty() && text.length() > 0) {
                // 删除明显的JSON结构或错误消息
                String cleanedText = text.replaceAll("[\\{\\}\\[\\]]", "")
                        .replaceAll("\"\\w+\":\\s*\"[^\"]*\"", "")
                        .replaceAll("error|exception|invalid", "");
                
                if (cleanedText.length() > 10) {
                    questions.add(new InterviewQuestion("未知", 
                            "API返回了无法解析的内容。原始响应片段: " + cleanedText.substring(0, Math.min(100, cleanedText.length())) + "...", 
                            "无法解析期望回答", 
                            "无法解析考察点"));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in fallback parsing: " + e.getMessage());
        }
        
        return questions;
    }

    /**
     * 检查一个领域是否属于指定的类别
     *
     * @param domain 领域名称
     * @param categoryIndex 类别索引（0：研发能力，1：技术管理能力，2：项目管理能力，3：需求分析能力）
     * @return 是否属于该类别
     */
    private boolean isInCategory(String domain, int categoryIndex) {
        String[][] categories = QuestionConfigActivity.DOMAIN_CATEGORIES;
        if (categoryIndex >= 0 && categoryIndex < categories.length) {
            String[] category = categories[categoryIndex];
            for (int i = 1; i < category.length; i++) { // 从1开始，跳过类别名称
                if (category[i].equals(domain)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 构建API请求
     * @param apiConfig API配置
     * @param requestBody 请求体JSON字符串
     * @return 构建好的请求对象
     */
    private Request buildRequest(ApiConfig apiConfig, String requestBody) {
        RequestBody body = RequestBody.create(requestBody, JSON);
        return new Request.Builder()
                .url(apiConfig.getApiUrl())
                .addHeader("Authorization", "Bearer " + apiConfig.getApiKey())
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
    }

    /**
     * 执行API请求，使用流式响应
     * @param context 上下文
     * @param request 请求对象
     * @param listener 回调监听器
     */
    private void executeRequest(Context context, Request request, OnQuestionsGeneratedListener listener) {
        // 使用流式响应方式处理请求
        isCancelled = false;
        String apiUrl = request.url().toString();
        String requestBody = "";
        
        try {
            // 从request中提取请求体
            if (request.body() != null) {
                RequestBody body = request.body();
                okio.Buffer buffer = new okio.Buffer();
                body.writeTo(buffer);
                requestBody = buffer.readUtf8();
            }
            
            // 获取API配置
            ApiConfig apiConfig = new ApiConfigManager(context).getApiConfig();
            if (apiConfig == null || !apiConfig.isValid()) {
                listener.onError("API配置无效");
                return;
            }
            
            // 执行流式API请求
            makeStreamingApiRequest(apiConfig, requestBody, listener);
        } catch (Exception e) {
            Log.e(TAG, "Error executing request", e);
            listener.onError("执行请求失败: " + e.getMessage());
        }
    }
} 